package org.balthie.demo.jdk.lang.ref;

import java.lang.ref.WeakReference;

// 弱引用也是用来描述非必需对象的，当JVM进行垃圾回收时，无论内存是否充足，都会回收被弱引用关联的对象。在java中，用java.lang.ref.WeakReference类来表示。
public class WeakReferenceDemo {
	public static void main(String[] args) {
		WeakReference<String> weak = new WeakReference<String>(new String("hello"));
		System.out.println(" weakRef " + weak + " referent is " + weak.get());
		System.gc(); // 通知JVM的gc进行垃圾回收
		System.out.println(" after gc weakRef " + weak + " referent is " + weak.get());
		// WeakReference 被强引用时自身不会被回收， 其持有的 referent gc时无条件被回收

		MyWeakRef myweak = new MyWeakRef(new String("hello"), 1000);
		System.out.println(" myweak " + myweak + " referent is " + myweak.get() + " value is " + myweak.value);
		System.gc(); // 通知JVM的gc进行垃圾回收
		System.out.println(" after gc myweak " + myweak + " referent is " + myweak.get() + " value is " + myweak.value);
		// WeakReference 被强引用时自身不会被回收， WeakReference强引用的成员变量 value也不会被回收
	}

	static class MyWeakRef extends WeakReference<String> {
		Integer value;

		public MyWeakRef(String referent, Integer value) {
			super(referent);
			this.value = value;
		}
	}
}
